package com.starblink.library.widget.product.pop

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.Point
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.view.updateLayoutParams
import com.blankj.utilcode.util.BarUtils
import com.starblink.android.basic.BuildConfig
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.extraOf
import com.starblink.android.basic.extension.navigationTo
import com.starblink.basic.ext.appScreenHeight
import com.starblink.basic.ext.load
import com.starblink.basic.ext.screenHeight
import com.starblink.basic.ext.screenWidth
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.CommUtils
import com.starblink.library.widget.databinding.PopFindSimilarWishlistBinding
import com.starblink.library.widget.databinding.PopFindSimilarWishlistKetaiBinding
import razerdp.basepopup.BasePopupWindow
import razerdp.blur.BlurImageView
import razerdp.blur.PopupBlurOption
import razerdp.util.PopupUtils
import razerdp.util.log.PopupLog

/**
 *  Create by yuanl at 2023/3/29
 **/
class WishListFindSimilarKetaiPop : BasePopupWindow {

    private val addBoardClick: () -> Unit

    constructor(
        context: Context,
        addBoardClick: () -> Unit
    ) : super(context) {
        this.addBoardClick = addBoardClick
    }

    constructor(
        dialog: Dialog,
        addBoardClick: () -> Unit
    ) : super(dialog) {
        this.addBoardClick = addBoardClick
    }

    private val binding = PopFindSimilarWishlistKetaiBinding.inflate(LayoutInflater.from(context))

    private var drawable: Drawable? = null

    private val anchorRect = Rect(-1, -1, -1, -1)

    private val screenW = screenWidth

    private val halfScreenW = screenWidth.shr(1)

    private val anchorTagScreenH = screenHeight * (3.0 / 5.0)

    private var imgUrl: String? = null

    private var productId: String? = ""

    private var type: Int? = null


    init {
        contentView = binding.root
        PopupLog.setOpenLog(BuildConfig.DEBUG)
    }

    override fun onViewCreated(contentView: View) {
        super.onViewCreated(contentView)
        binding.img.enableCorner(16.dp2px())
        binding.btnFind.enableCorner(16.dp2px(), "top")
        binding.btnAdd.enableCorner(16.dp2px(), "bottom")

        //setBlurBackgroundEnable(true)

        /*setBlurOption(
            PopupBlurOption().setFullScreen(false).setBlurInDuration(-1L)
                .setBlurOutDuration(-1L)
                .setBlurRadius(10F)
                .setBlurView(context?.window?.decorView)
                .setBlurPreScaleRatio(0.25F)
                .setFullScreen(false)
        )*/
        setBackgroundColor(context.color(com.starblink.basic.style.R.color.clr_ad0f172a))

        binding.img.scaleType = ImageView.ScaleType.CENTER_INSIDE

        binding.btnFind.click {
            dismiss()

            if (imgUrl.isNullOrEmpty() || productId.isNullOrEmpty() || type == null) {
                return@click
            }

            CommonRoute.toFindSimilarGoods(
                imgUrl!!,
                productId!!,
                this@WishListFindSimilarKetaiPop.type!!
            )
            /*navigationTo(RoutePage.ImageSearch.PAGE_FIND_SIMILAR) {
                extraOf(RoutePage.ImageSearch.ARGS_IMG_URL to imgUrl,
                    RoutePage.ARG.ID to productId,
                    RoutePage.ARG.TYPE to this@GoodsFindSimilarPop.type)
            }*/
        }
        binding.btnAdd.setOnClickListener {
            dismiss()
            addBoardClick.invoke()
        }


        binding.root.setOnClickListener {
            dismiss()
        }


    }

    override fun onBeforeShow(): Boolean {
        val superVal = super.onBeforeShow()

        if (drawable != null) {
            binding.img.setImageDrawable(drawable)
        } else {
            binding.img.load(imgUrl)
        }


        val overWidth = anchorRect.width() * SCALE >= screenW

        if (anchorRect.left > -1 && anchorRect.top > -1) {
            (binding.img.layoutParams as ConstraintLayout.LayoutParams?)?.run {
                width = if (overWidth) anchorRect.width() else (anchorRect.width() * SCALE).toInt()
                height =
                    if (overWidth) anchorRect.height() else (anchorRect.height() * SCALE).toInt()
                if (overWidth) {
                    leftMargin = 0
                    rightMargin = 0

                    leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID
                    rightToRight = ConstraintLayout.LayoutParams.PARENT_ID
                } else {
                    leftMargin = 12.dp2px()
                    rightMargin = 12.dp2px()

                    if (anchorRect.left < halfScreenW) {
                        leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID
                        rightToRight = ConstraintLayout.LayoutParams.UNSET
                    } else {
                        leftToLeft = ConstraintLayout.LayoutParams.UNSET
                        rightToRight = ConstraintLayout.LayoutParams.PARENT_ID
                    }
                }
                if (anchorRect.bottom < anchorTagScreenH || anchorRect.top <= actionVHeight) {
                    topToBottom = ConstraintLayout.LayoutParams.UNSET
                    topToTop = ConstraintLayout.LayoutParams.PARENT_ID
                    bottomToBottom = ConstraintLayout.LayoutParams.UNSET
                } else {
                    topToBottom = binding.vBgAction.id
                    topToTop = ConstraintLayout.LayoutParams.UNSET
                    bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
                }
            }
            binding.vBgAction.updateLayoutParams<ConstraintLayout.LayoutParams> {
                if (overWidth) {
                    leftToLeft = binding.img.id
                    rightToRight = binding.img.id
                } else {
                    if (anchorRect.left < halfScreenW) {
                        leftToLeft = binding.img.id
                        rightToRight = ConstraintLayout.LayoutParams.UNSET
                    } else {
                        leftToLeft = ConstraintLayout.LayoutParams.UNSET
                        rightToRight = binding.img.id
                    }
                }
                if (anchorRect.bottom < anchorTagScreenH || anchorRect.top <= actionVHeight) {
                    topToBottom = binding.img.id
                    topToTop = ConstraintLayout.LayoutParams.UNSET
                    bottomToTop = ConstraintLayout.LayoutParams.UNSET
                } else {
                    topToBottom = ConstraintLayout.LayoutParams.UNSET
                    topToTop = ConstraintLayout.LayoutParams.PARENT_ID
                    bottomToTop = binding.img.id
                }
            }
        }
        return superVal
    }

    private fun prepare(anchorView: View): Point {
        //anchorView.getGlobalVisibleRect(anchorRect)
        val array = intArrayOf(0, 0)
        anchorView.getLocationInWindow(array)
        anchorRect.set(
            array[0],
            array[1],
            array[0] + anchorView.measuredWidth,
            array[1] + anchorView.measuredHeight
        )
        drawable = (anchorView as? ImageView?)?.drawable

        val scaleH = if (anchorRect.width() * SCALE >= screenW) {
            anchorRect.height()
        } else (anchorRect.height() * SCALE).toInt()
        val point = Point(anchorRect.left, anchorRect.top - (scaleH - anchorRect.height()).shr(1))


        val contentEstimateH = actionVHeight + scaleH

        val bottomHeight = bottomHeight()
        if (anchorRect.top < 0) {
            point.y = 0
        } else if (anchorRect.bottom >= bottomHeight) {
            point.y = bottomHeight - contentEstimateH.toInt()
        } else if (anchorRect.bottom > anchorTagScreenH) {
            point.y = anchorRect.top - actionVHeight.toInt()
        }
        return point
    }

    private fun bottomHeight() = (context?.let {
        (screenHeight - (if (BarUtils.isNavBarVisible(it)) CommUtils.getBottomStatusHeight() else 0))
    } ?: appScreenHeight)

    private val actionVHeight: Float =
        (binding.vBgAction.layoutParams as ConstraintLayout.LayoutParams?)?.let {
            ((it.matchConstraintPercentWidth * screenW / (200.0f / 93.0f)) + it.topMargin + it.bottomMargin)
        } ?: 0F


    fun showPopup(anchorView: View, imgUrl: String, productId: String, type: Int) {
        val p = prepare(anchorView)
        this.imgUrl = imgUrl
        this.productId = productId
        this.type = type
        showPopupWindow(p.x, p.y)
    }

    companion object {

        private const val SCALE = 1.2f

    }
}